import {
  asyncRoutes,
  constantRoutes
} from '@/router'
const state = {
  routes: [],
  nowPath: {},
  pageRule: [],
  pageRuleArr: [],

}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_NOWPATH: (state, nowPath) => {
    state.nowPath = nowPath;
    if (nowPath.meta && nowPath.meta.allRole) {
      state.pageRule = nowPath.meta.allRole
    } else { //此页面没有权限配置
      state.pageRule = []
    }
  },
  SET_RULEARR: (state, pageRuleArr) => {
    state.pageRuleArr = pageRuleArr;
  },
}
/*
    将路由与映射表关联
*/
function mapList(router, menu) {
  const res = [];
  router.forEach(e => {
    let t = {
        ...e
      },
      m = getMenu(t.name, menu);
    if (m || t.hidden) {
      if (!t.hidden && m.children.length != 0 && t.children && t.children.length != 0) {
        t.children = mapList(t.children, m.children)
      }
      // 按钮权限list
      let buttonList = m.children.filter(item=>item.type=='F');
      t.meta.allRole = allRole(getButtons(buttonList));
      // if (m.buttonList && m.buttonList.length != 0) {
      //   t.meta.allRole = allRole(m.buttonList);
      // }
      t.meta.title=m.name;
      res.push(t)
    }
  })
  return res;
}
// 获取按钮权限list
function getButtons(menu){
  let buttonList = menu.map(e=>{
    if(e.type =='F'){//（M(1)目录 C(2)菜单 F(3)按钮）
      return e;
    }
  });
  return buttonList;
}
/* 获取 返回菜单数据与路由对应的数据 */
function getMenu(name, menu) {
  let res = null;
  menu.forEach(e => {
    if (e.enName == name) {
      if(e.type=='M'){//目录
        if(e.children.length>0){
          res = e;
        }
      }else{
        res = e;
      }
    }
  })
  return res;
}
/*
  初始化路由数据对应的 rulesPath
*/
function routerBuding(router, kename = '') {
  const res = [];
  router.forEach(e => {
    let t = {
      ...e
    }
    let name = kename ? `${kename}:` : kename
    t.rulesPath = `${name}${t.name}`
    if (t.children) {
      t.children = routerBuding(t.children, t.rulesPath)
    }
    res.push(t)
  })
  return res;
}
/*
  获取页面内权限
*/
function allRole(pageRuleList) {
  let arr = [];
  pageRuleList.forEach(e => {
    let s = e.perms;
    arr.push(s)
  })
  return arr;
}

const actions = {
  generateRoutes({
    commit,
    dispatch
  }, menu) {
    return new Promise(async resolve => {
      let accessedRoutes = mapList(routerBuding(asyncRoutes), menu);
      commit('SET_ROUTES', accessedRoutes);
      accessedRoutes = accessedRoutes.concat([{
        path: '*',
        component: () => import('@/views/404'),
        redirect: '/404'
      }])
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
